package com.mysharding.shardingUtils;

import com.alibaba.fastjson.JSON;
import org.apache.shardingsphere.sharding.api.sharding.complex.ComplexKeysShardingAlgorithm;
import org.apache.shardingsphere.sharding.api.sharding.complex.ComplexKeysShardingValue;

import java.util.*;

public class ComplexShardingAlgorithm implements ComplexKeysShardingAlgorithm {


    @Override
    public Collection<String> doSharding(Collection availableTargetNames, ComplexKeysShardingValue shardingValue) {
        //范围分片
        Map columnNameAndShardingValuesMap = shardingValue.getColumnNameAndShardingValuesMap();
        Object user_id = columnNameAndShardingValuesMap.get("user_id");

        List<Integer> list = castList(user_id, Integer.class);
        List<String> stringList = new ArrayList<>();
        Integer i = list.get(0) % 2;

        System.err.println("-======>" + JSON.toJSON(i));
        stringList.add("sys_user" + i);

        return stringList;
    }

    public static <T> List<T> castList(Object obj, Class<T> clazz) {
        List<T> result = new ArrayList<T>();
        if (obj instanceof List<?>) {
            for (Object o : (List<?>) obj) {
                result.add(clazz.cast(o));
            }
            return result;
        }
        return null;
    }

    @Override
    public void init() {

    }

    @Override
    public String getType() {
        return "COMPLEX";
    }
}
